﻿namespace BM.Tools.Xml.Schema
{
    using System.Collections.Generic;
    using System.Xml.Schema;

    /// <summary>
    /// This class provides helper methods for searching the tree of <see cref="IVisited"/> objects.
    /// </summary>
    public static class VisitedExtensions
    {
        /// <summary>
        /// Gets the children of the given type.
        /// </summary>
        /// <param name="current">
        /// The current IVistited object.
        /// </param>
        /// <typeparam name="TVisited">
        /// The type of the searched children.
        /// </typeparam>
        /// <returns>
        /// The children of the given type.
        /// </returns>
        public static IEnumerable<TVisited> GetChildren<TVisited>(this IVisited current)
            where TVisited : class, IVisited
        {
            var list = new List<TVisited>();
            foreach (var visited in current.Children)
            {
                if (typeof(TVisited).IsAssignableFrom(visited.GetType()))
                {
                    list.Add(visited as TVisited);
                }
                else
                {
                    list.AddRange(visited.GetChildren<TVisited>());
                }
            }

            return list;
        }
        
        /// <summary>
        /// Determines whether the specified schemaObject is the schema object of the ancestor of the current <see cref="IVisited"/> object.
        /// </summary>
        /// <param name="current">
        /// The current <see cref="IVisited"/> object.
        /// </param>
        /// <param name="schemaObject">
        /// The schemaObject.
        /// </param>
        /// <returns>
        /// <c>true</c> if schemaObject specified schemaObject is the schema object of the ancestor of the current; otherwise, <c>false</c>.
        /// </returns>
        public static bool IsAncestorOf(this IVisited current, XmlSchemaObject schemaObject)
        {
            if (current.Parent == null)
            {
                return false;
            }

            return current.Parent.SchemaObject.Equals(schemaObject) || current.Parent.IsAncestorOf(schemaObject);
        }
    }
}
